def rail_fence_decrypt(ciphertext, num_rails):
    """
    解密栅栏密码。

    参数:
    ciphertext (str): 加密后的文本。
    num_rails (int): 栅栏的行数。

    返回:
    str: 解密后的明文。
    """
    # 计算每个周期的长度
    cycle_length = 2 * num_rails - 2

    # 初始化栅栏矩阵
    fence = [['' for _ in range(len(ciphertext))] for _ in range(num_rails)]

    # 确定每个字符在栅栏中的位置
    index = 0
    for rail in range(num_rails):
        pos = rail
        step = 0
        while pos < len(ciphertext):
            fence[rail][pos] = '*'
            if rail == 0 or rail == num_rails - 1:
                pos += cycle_length
            else:
                pos += cycle_length - 2 * step if step % 2 == 0 else 2 * step
            step += 1

    # 填充栅栏矩阵
    index = 0
    for rail in range(num_rails):
        for pos in range(len(ciphertext)):
            if fence[rail][pos] == '*':
                fence[rail][pos] = ciphertext[index]
                index += 1

    # 按照栅栏路径读取明文
    plaintext = ''
    pos = 0
    rail = 0
    direction = 1
    while pos < len(ciphertext):
        plaintext += fence[rail][pos]
        pos += 1
        rail += direction
        if rail == 0 or rail == num_rails - 1:
            direction = -direction

    return plaintext

# 测试解密函数
if __name__ == "__main__":
    ciphertext = "felhaagv{ewtehtehfilnakgw}"   #原始加密文本
    num_rails = 3
    print("原始加密文本:", ciphertext)
    decrypted_text = rail_fence_decrypt(ciphertext, num_rails)
    print("解密后的明文:", decrypted_text)
